import React from 'react'
import { observable, action, toJS, computed } from 'mobx';
import { SearchAdvanced, ListAdvanced, RouteLayout, TreePage, Browser } from 'weaver-mobile-page';
import { Tools, Modal, Toast, Bubble } from 'weaver-mobile';
import * as TaskMainApis from '../../api/task/taskMain'
import TaskCommonStore from './TaskCommonStore';

const taskCommonStore = new TaskCommonStore()
const getLabel = Tools.getLabel

export default class TaskMainStore {

  @observable
  advancedSearchPopoverVisible = false

  @action
  changeAdvancedSearchPopoverVisible = (advancedSearchPopoverVisible) => {
    this.advancedSearchPopoverVisible = advancedSearchPopoverVisible
  }

  //组织树
  @observable 
  orgTreeStore = new TreePage.Store({ route: '/taskHome/taskMain' })
  
  @observable
  viewTypeList = [
    {
      key: "5",
      iconclass: "customer",
      title: getLabel(382491, '个人Todolist视图')
    },
    {
      key: "2",
      iconclass: "blog-chidao",
      title: getLabel(382493, '到期日分类视图')
    },
    {
      key: "3",
      iconclass: "list",
      title: getLabel(382495, '紧急程度分类视图')
    },
    {
      key: "1",
      iconclass: "more-3",
      title: getLabel(82532, '列表视图')
    },
    {
      key: "4",
      iconclass: "organization",
      title: getLabel(382496, '层级视图')
    }
  ]

  @observable
  taskStatusOptions = [
    {
      label: getLabel(332, '全部'),
      value: "0"
    },
    {
      label: getLabel(1960, '进行中'),
      value: "1"
    },
    {
      label: getLabel(515068, "待确认"),
      value: "4"
    },
    {
      label: getLabel(83221, "已拒绝"),
      value: "5"
    },
    {
      label: getLabel(19134, "审批中"),
      value: "6"
    },
    {
      label: getLabel(23774, '已完成'),
      value: "2"
    }
  ]

  @observable
  viewId = ""

  @action
  changeViewId = (viewId) => {
    this.viewId = viewId
  }

  @observable
  selectViewType = "5"

  @action
  changeSelectViewType = (type) => {
    this.selectViewType = type
  }

  @observable
  selectTaskStatus = "1"

  @action
  changeSelectTaskStatus = (status) => {
    this.selectTaskStatus = status
  }

  defaultCondtype = "-1"

  @observable
  condtype = ""

  @action
  changeCondtype = (condtype) => {
    this.condtype = condtype
  }

  @observable
  newMap = {}

  @action
  changeNewMap = (newMap) => {
    this.newMap = newMap
  }

  @computed
  get bottomMenuDatas() {
    return [
      {
        key: "1",
        menuname: getLabel(19865, '我的任务'),
        rightContent: this.newMap["1"] > 0 ? this.newMap["1"] : ""
      },
      {
        key: "3",
        menuname: getLabel(382482, '我负责的任务'),
        rightContent: this.newMap["3"] > 0 ? this.newMap["3"] : ""
      },
      {
        key: "4",
        menuname: getLabel(382483, '我参与的任务'),
        rightContent: this.newMap["4"] > 0 ? this.newMap["4"] : ""
      },
      {
        key: "6",
        menuname: getLabel(382484, '我关注的任务'),
        rightContent: this.newMap["6"] > 0 ? this.newMap["6"] : ""
      },
      {
        key: "2",
        menuname: getLabel(382485, '我创建的任务'),
        rightContent: this.newMap["2"] > 0 ? this.newMap["2"] : ""
      },
      {
        key: "8",
        menuname: getLabel(382486, '我分配的任务'),
        rightContent: this.newMap["8"] > 0 ? this.newMap["8"] : ""
      },
      {
        key: "5",
        menuname: getLabel(382492, '分享给我的任务'),
        rightContent: this.newMap["5"] > 0 ? this.newMap["5"] : ""
      },
      {
        key: "0",
        menuname: getLabel(382488, "所有任务")
      },
      {
        key: "7",
        menuname: getLabel(382494, "已完成新反馈任务"),
        rightContent: this.newMap["7"] > 0 ? this.newMap["7"] : ""
      },
      {
        key: "9",
        menuname: getLabel(508734, '下属任务')
      }
    ]
  }

  @observable
  bottomMenuVisible = false

  @action
  changeBottomMenuVisible = (bottomMenuVisible) => {
    this.bottomMenuVisible = bottomMenuVisible
  }

  @observable
  advancedParams = {
    taskname: "",
    principal: [],
    urgentLevel: "",
    begindate: "",
    begindate1: "",
    enddate: "",
    enddate1: "",
    orderby: "",
    orderbytype: "",
    // tag: "",
    tagArray: [],
    subordinate: []
  }
  btnBgcolorArray = {
    complete: "rgba(77, 122, 216, 1)", progress: "rgba(77, 122, 216, 1)",
    special: "rgba(245, 154, 35, 1)", canclespecial: "rgba(245, 154, 35, 1)",
    addfb: "rgba(170, 170, 170, 1)", "delete": "#333", tag: "#8FBC8F", confirmed: "#eaa81c",
    refuse: "#d81d19", submitAudit: "rgb(241, 2, 46)"
  }
  @action
  changeAdvancedParams = (advancedParams) => {
    this.advancedParams = advancedParams
  }

  @action
  clearAdvancedParams = () => {
    this.advancedParams.taskname = "",
      this.advancedParams.principal = [],
      this.advancedParams.urgentLevel = "",
      this.advancedParams.begindate = "",
      this.advancedParams.begindate1 = "",
      this.advancedParams.enddate = "",
      this.advancedParams.enddate1 = "",
      this.advancedParams.orderby = "",
      this.advancedParams.orderbytype = "",
      // this.advancedParams.tag = "",
      this.advancedParams.tagArray = [],
      this.advancedParams.subordinate = []
  }

  // 获取任务列表后台返回的datas数据
  @observable
  taskListBackendDatas = []

  @action
  setTaskBackendDatas = (datas) => {
    this.taskListBackendDatas = datas
  }

  // 层级列表组件实际使用数据
  @observable
  taskListDatas = []

  @action
  changeTaskListDatas = (datas) => {
    this.taskListDatas = datas
  }

  @observable
  hasmore = "1"

  @action
  changeHasmore = (hasmore) => {
    this.hasmore = hasmore
  }

  @observable
  showGetMore = false

  @action
  changeShowGetMore = (showGetMore) => {
    this.showGetMore = showGetMore
  }


  @observable
  pagenum = 1

  @action
  changePagenum = (pagenum) => {
    this.pagenum = pagenum
  }

  @observable
  total = 0

  @action
  changeTotal = (total) => {
    this.total = total
  }

  @action
  initTaskListDatas = () => {
    let datas = []
    this.taskListBackendDatas.forEach((d, i) => {
      datas.push(this.formatBackendData(d))
    })
    this.taskListDatas = datas
  }

  @observable
  showBatchChoose = false

  @action
  changeShowBatchChoose = (value) => {
    this.showBatchChoose = value
  }

  @observable
  isBatchChoosed = false

  @action
  changeIsBatchChoosed = (val) => {
    this.isBatchChoosed = val
  }

  @action
  clearBatchInfo = () => {
    this.changeIsBatchChoosed(false)
    this.batchChoose(false)
    this.changeShowBatchChoose(false)
  }

  @computed
  get batchChooseNum() {
    return this.taskListDatas.filter((d, i) => d.checked).length
  }

  @action
  batchChoose = (choose = true) => {
    this.taskListDatas.forEach((d, i) => {
      d.checked = choose
    })
  }

  @action
  onTaskCheckedChange = (taskid, checked) => {
    this.taskListDatas.forEach((d, i) => {
      if (d.id == taskid) {
        d.checked = checked
      }
    })
  }

  @action
  batchSetTagOperation = (params) => {
    const { tagtype } = params
    if (tagtype == "3") {  // 清除标签
      Modal.alert(getLabel('386786', '信息确认'), params.infos, [
        { text: getLabel(201, '取消'), style: 'default' },
        {
          text: getLabel('826', '确定'),
          onPress: () => {
            this.doBatchSetTag(params)
          }
        }
      ])
    } else {
      this.doBatchSetTag(params)
    }
  }

  @action
  doBatchSetTag = (params) => {
    const { tagids, tagtype, opentagtype, doback } = params
    taskCommonStore.showLoading()
    TaskMainApis.editTaskInfo({
      fieldname: "tag",
      opentagtype,
      tagtype,
      taskids: "," + this.taskListDatas.filter((d, i) => d.checked).map((d, i) => d.id).join(","),
      addvalue: tagids
    }).then(res => {
      if (res.status == "1") {
        if (tagtype == "3") {
          this.taskListDatas.forEach((task, ti) => {
            if (task.checked) {
              task.tags = []
            }
          })
        } else {
          if (res.taskTagMap) {
            for (let k in res.taskTagMap) {
              this.taskListDatas.forEach((task, ti) => {
                if (task.id == k) {
                  task.tags = res.taskTagMap[k] || []
                }
              })
            }
          }
        }
      } 
      this.taskListDatas = [...this.taskListDatas]
      this.clearBatchInfo()
      taskCommonStore.closeLoading()
      typeof doback === "function" && doback(res)
    })
  }

  @action
  formatBackendData = (d) => {
    return {
      ...d,
      id: d.key,
      originalData: d,
      user: d.principalname,
      date: d.enddate,
      commentCount: d.fbcount,
      hasChildren: d.childcount && parseInt(d.childcount + "") > 0,
      childrenOpen: d.isopen,
      comsbtn: d.comsbtn.filter((btn, i) => {
        return btn.type != "tag"
        // return btn.type != ""
      }).reverse().map((btn, i) => {
        return {
          type: btn.type,
          text: btn.com,
          onPress: () => { this.getSwipeBtnCallback(btn.type)(d.key, btn.type) },
          style: {
            backgroundColor: this.getSwipeBtnBgcolor(btn.type),
            color: 'white',
            padding: "0 10px",
            maxWidth: 75,
            minWidth: 40
          }
        }
      }),
      checked: false
    }
  }

  // 获取任务列表后台返回的datetype数据
  @observable
  taskListDatetype = []

  @action
  setTaskListDatetype = (datetype) => {
    this.taskListDatetype = datetype
  }

  @action
  getSwipeBtnCallback = (btntype) => {
    if (btntype == "complete" || btntype == "progress") {
      return this.onTaskChangeStatus
    } else if (btntype == "special" || btntype == "canclespecial") {
      return this.onTaskMarkAttension
    } else if (btntype == "addfb") {
      return this.onTaskAddFb
    } else if (btntype == "delete") {
      return this.onTaskDelete
    } else if (btntype == "tag") {
      return this.onTaskMarkTag
    } else {
      return () => {
        console.log("can`t revolve this btntype")
      }
    }
  }

  @action
  getSwipeBtnBgcolor = (btntype) => {
    return this.btnBgcolorArray[btntype]
  }
  @action
  onTaskChangeStatus = (taskid, btntype) => {
    Modal.alert(getLabel('386786', '信息确认'), btntype == "complete" ? getLabel(508674, '确认要标记此任务为完成吗？') : getLabel(508676, '确认要标记此任务为进行中吗？'), [
      {
        text: getLabel(201, '取消'),
        style: 'default'
      },
      {
        text: getLabel('826', '确定'),
        onPress: () => {
          TaskMainApis.changeTaskStatus({
            taskId: taskid,
            status: btntype == "complete" ? "2" : "1"
          }).then(res => {
            if (res && res.status == "1") {
              Bubble.success(getLabel(31439, '更新成功!'), 1)

              let result = this.getDataByRecursion(this.taskListDatas, taskid)
              if (btntype == "complete") {
                result.data.status = res.newstatus || "2"
              } else if (btntype == "progress") {
                result.data.status = "1"
              }
              result.data.comsbtn.forEach((btn, i) => {
                if (btn.type === btntype) {
                  result.data.comsbtn[i] = {
                    type: res.smap.type,
                    text: res.smap.com,
                    onPress: () => { this.getSwipeBtnCallback(res.smap.type)(taskid, res.smap.type) },
                    style: { backgroundColor: this.getSwipeBtnBgcolor(res.smap.type), color: 'white', padding: "0 6px" }
                  }
                }
              })

              this.changeTaskListDatas([...this.taskListDatas])
            }
          })
        }
      }
    ])
  }

  @action
  onTaskMarkAttension = (taskid, btntype) => {
    TaskMainApis.setSpecial({
      taskid,
      special: btntype == "special" ? "0" : "1"
    }).then(res => {
      if (res && res.status == "1") {
        Bubble.success(btntype == "special" ? getLabel(503769, '关注成功!') : getLabel(503772, '取消关注成功!'), 1)

        let result = this.getDataByRecursion(this.taskListDatas, taskid)
        result.data.comsbtn.forEach((btn, i) => {
          if (btn.type === btntype) {
            result.data.comsbtn[i] = {
              type: res.smap.type,
              text: res.smap.com,
              onPress: () => { this.getSwipeBtnCallback(res.smap.type)(taskid, res.smap.type) },
              style: { backgroundColor: this.getSwipeBtnBgcolor(res.smap.type), color: 'white', padding: "0 12px" }
            }
          }
        })

        this.changeTaskListDatas([...this.taskListDatas])
      } else {
        Bubble.error((btntype == "special" ? getLabel(25436, '关注') : getLabel(26938, '取消关注')) + getLabel('25009', '失败'), 1)
      }
    })
  }

  //监听此对象发生改变时自动跳转到详情反馈页
  @observable
  jumpTaskFbMonitor = {}

  @action
  changeJumpTaskMonitor = (jumpTaskFbMonitor) => {
    this.jumpTaskFbMonitor = jumpTaskFbMonitor
  }

  @action
  onTaskAddFb = (taskid, btntype) => {
    this.changeJumpTaskMonitor({
      taskid
    })
  }

  @action
  onTaskDelete = (taskid, btntype) => {
    Modal.alert(getLabel('386786', '信息确认'), getLabel(508794, '确认要删除此任务吗？'), [
      {
        text: getLabel(201, '取消'),
        style: 'default'
      },
      {
        text: getLabel('826', '确定'),
        onPress: () => {
          TaskMainApis.changeTaskStatus({
            taskId: taskid,
            status: "4"
          }).then(res => {
            if (res.status == 1) {
              Bubble.success(getLabel(83472, '删除成功!'), 1)

              let result = this.getDataByRecursion(this.taskListDatas, taskid)
              result.belongArr.splice(result.belongArr.indexOf(result.data), 1)
              this.changeTaskListDatas([...this.taskListDatas])
              this.changeTotal(this.total - 1)
            }
          })
        }
      }
    ])
  }

  @action
  onTaskMarkTag = (taskid, btntype) => {

  }

  @action
  onTaskGetMore = (obj) => {
    const { id, pagenum, total } = obj.datetype

    Toast.loading('Loading...', 0)
    TaskMainApis.getMoreTaskList({
      index: id - 1,
      cate: id,
      pagenum: pagenum + 1,
      total,
      sorttype: this.selectViewType,
      orderbytype: "desc",
      pagesize: this.selectViewType == "1" || this.selectViewType == "4" ? "10" : "5",
      condtype: this.condtype,
      status: this.selectTaskStatus
    }).then(res => {
      Toast.hide()
      res.datas.forEach((d, i) => {
        this.taskListDatas.push(this.formatBackendData(d))
      })
      obj.datetype.isopen = true
      obj.datetype.pagenum += 1
      obj.datetype.hasmore = res.hasmore
      obj.datetype.showGetMore = true
    })
  }


  @observable
  onTaskGetMore1 = (obj) => {
    const { pagenum, total } = obj.other

    Toast.loading('Loading...', 0)
    TaskMainApis.getMoreTaskList({
      index: 0,
      pagenum: pagenum + 1,
      total,
      sorttype: this.selectViewType,
      orderbytype: "desc",
      pagesize: this.selectViewType == "1" || this.selectViewType == "4" ? "10" : "5",
      condtype: this.condtype,
      status: this.selectTaskStatus
    }).then(res => {
      Toast.hide()
      res.datas.forEach((d, i) => {
        this.taskListDatas.push(this.formatBackendData(d))
      })
      this.changePagenum(pagenum + 1)
      this.changeHasmore(res.hasmore)
      this.changeShowGetMore(true)
    })
  }

  // @action
  getDataByRecursion = (targetDatas, targetDataId, res = {}) => {
    if (targetDatas && targetDatas.length > 0) {
      for (let i = 0; i < targetDatas.length; i++) {
        if (targetDatas[i].id == targetDataId) {
          res.data = targetDatas[i]
          res.belongArr = targetDatas
        }
        this.getDataByRecursion(targetDatas[i].children, targetDataId, res)
      }
    }
    return res
  }

}